package com.ruoyi.web.controller.business;

import com.ruoyi.business.domain.Order;
import com.ruoyi.business.domain.WxUserAddress;
import com.ruoyi.business.service.IOrderService;
import com.ruoyi.business.service.IUserAddressService;
import com.ruoyi.common.core.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信小程序订单接口
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/wx/miniapp/order")
public class WxOrderController
{
    private static final Logger log = LoggerFactory.getLogger(WxOrderController.class);

    @Autowired
    private IOrderService orderService;
    
    @Autowired
    private IUserAddressService userAddressService;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public AjaxResult createOrder(@RequestBody Order order)
    {
        try
        {
            if (order == null || order.getOpenid() == null || order.getOpenid().isEmpty())
            {
                return AjaxResult.error("订单信息不能为空");
            }
            
            if (order.getAddressId() == null)
            {
                return AjaxResult.error("请选择收货地址");
            }
            
            // 获取收货地址信息
            WxUserAddress address = userAddressService.selectUserAddressById(order.getAddressId());
            if (address == null)
            {
                return AjaxResult.error("收货地址不存在");
            }
            
            // 设置收货信息
            order.setReceiverName(address.getReceiverName());
            order.setReceiverPhone(address.getReceiverPhone());
            order.setReceiverAddress(address.getProvince() + address.getCity() + address.getDistrict() + address.getDetailAddress());
            
            // 设置初始订单状态：待支付
            order.setStatus("0");
            
            int result = orderService.insertOrder(order);
            if (result > 0)
            {
                Map<String, Object> data = new HashMap<>();
                data.put("orderId", order.getOrderId());
                return AjaxResult.success("创建成功", data);
            }
            return AjaxResult.error("创建失败");
        }
        catch (Exception e)
        {
            log.error("创建订单异常", e);
            return AjaxResult.error("创建失败，请稍后重试");
        }
    }

    /**
     * 获取订单列表
     */
    @GetMapping("/list")
    public AjaxResult getOrderList(@RequestParam String openid, @RequestParam(required = false) String status)
    {
        try
        {
            if (openid == null || openid.isEmpty())
            {
                return AjaxResult.error("用户openid不能为空");
            }

            List<Order> orders = orderService.selectOrderList(openid, status);
            return AjaxResult.success(orders);
        }
        catch (Exception e)
        {
            log.error("获取订单列表异常", e);
            return AjaxResult.error("获取订单列表失败，请稍后重试");
        }
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/detail/{orderId}")
    public AjaxResult getOrderDetail(@PathVariable Long orderId)
    {
        try
        {
            if (orderId == null)
            {
                return AjaxResult.error("订单ID不能为空");
            }

            Order order = orderService.selectOrderById(orderId);
            if (order == null)
            {
                return AjaxResult.error("订单不存在");
            }

            return AjaxResult.success(order);
        }
        catch (Exception e)
        {
            log.error("获取订单详情异常", e);
            return AjaxResult.error("获取订单详情失败，请稍后重试");
        }
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel/{orderId}")
    public AjaxResult cancelOrder(@PathVariable Long orderId)
    {
        try
        {
            if (orderId == null)
            {
                return AjaxResult.error("订单ID不能为空");
            }

            int result = orderService.cancelOrder(orderId);
            if (result > 0)
            {
                return AjaxResult.success("取消成功");
            }
            return AjaxResult.error("取消失败");
        }
        catch (Exception e)
        {
            log.error("取消订单异常", e);
            return AjaxResult.error("取消失败，请稍后重试");
        }
    }

    /**
     * 支付订单
     */
    @PostMapping("/pay/{orderId}")
    public AjaxResult payOrder(@PathVariable Long orderId)
    {
        try
        {
            if (orderId == null)
            {
                return AjaxResult.error("订单ID不能为空");
            }

            // 模拟调用微信支付接口
            int result = orderService.payOrder(orderId);
            if (result > 0)
            {
                return AjaxResult.success("支付成功");
            }
            return AjaxResult.error("支付失败");
        }
        catch (Exception e)
        {
            log.error("支付订单异常", e);
            return AjaxResult.error("支付失败，请稍后重试");
        }
    }

    /**
     * 申请退款
     */
    @PostMapping("/refund/{orderId}")
    public AjaxResult refundOrder(@PathVariable Long orderId, @RequestParam(required = false) String reason)
    {
        try
        {
            if (orderId == null)
            {
                return AjaxResult.error("订单ID不能为空");
            }

            int result = orderService.refundOrder(orderId, reason);
            if (result > 0)
            {
                return AjaxResult.success("申请退款成功");
            }
            return AjaxResult.error("申请退款失败");
        }
        catch (Exception e)
        {
            log.error("申请退款异常", e);
            return AjaxResult.error("申请退款失败，请稍后重试");
        }
    }

    /**
     * 确认收货
     */
    @PostMapping("/confirm/{orderId}")
    public AjaxResult confirmOrder(@PathVariable Long orderId)
    {
        try
        {
            if (orderId == null)
            {
                return AjaxResult.error("订单ID不能为空");
            }

            int result = orderService.confirmOrder(orderId);
            if (result > 0)
            {
                return AjaxResult.success("确认成功");
            }
            return AjaxResult.error("确认失败");
        }
        catch (Exception e)
        {
            log.error("确认收货异常", e);
            return AjaxResult.error("确认失败，请稍后重试");
        }
    }
    
    /**
     * 评价订单
     */
    @PostMapping("/review")
    public AjaxResult reviewOrder(@RequestParam Long orderId, @RequestParam Integer rating, @RequestParam(required = false) String comment)
    {
        try
        {
            if (orderId == null)
            {
                return AjaxResult.error("订单ID不能为空");
            }
            
            if (rating == null || rating < 1 || rating > 5)
            {
                return AjaxResult.error("请选择有效的评分(1-5)");
            }

            int result = orderService.reviewOrder(orderId, rating, comment);
            if (result > 0)
            {
                return AjaxResult.success("评价成功");
            }
            return AjaxResult.error("评价失败");
        }
        catch (Exception e)
        {
            log.error("评价订单异常", e);
            return AjaxResult.error("评价失败，请稍后重试");
        }
    }
    
    /**
     * 删除订单(仅支持已完成或已取消的订单)
     */
    @PostMapping("/delete/{orderId}")
    public AjaxResult deleteOrder(@PathVariable Long orderId)
    {
        try
        {
            if (orderId == null)
            {
                return AjaxResult.error("订单ID不能为空");
            }

            int result = orderService.deleteOrder(orderId);
            if (result > 0)
            {
                return AjaxResult.success("删除成功");
            }
            return AjaxResult.error("删除失败");
        }
        catch (Exception e)
        {
            log.error("删除订单异常", e);
            return AjaxResult.error("删除失败，请稍后重试");
        }
    }
    
    /**
     * 再次购买
     */
    @PostMapping("/rebuy/{orderId}")
    public AjaxResult rebuyOrder(@PathVariable Long orderId)
    {
        try
        {
            if (orderId == null)
            {
                return AjaxResult.error("订单ID不能为空");
            }

            Order newOrder = orderService.rebuyOrder(orderId);
            if (newOrder != null)
            {
                Map<String, Object> data = new HashMap<>();
                data.put("orderId", newOrder.getOrderId());
                return AjaxResult.success("创建成功", data);
            }
            return AjaxResult.error("创建失败");
        }
        catch (Exception e)
        {
            log.error("再次购买异常", e);
            return AjaxResult.error("创建失败，请稍后重试");
        }
    }
}